package com.cspm.ahjy.bc.office.word.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.dom4j.Attribute;
import org.dom4j.Element;
import org.springframework.util.StringUtils;

import sun.misc.BASE64Decoder;

import com.cspm.ahjy.bc.office.enums.AlignEnum;
import com.cspm.ahjy.bc.office.enums.ColorEnum;
import com.cspm.ahjy.bc.office.util.ImageFileUtil;
import com.cspm.ahjy.bc.office.util.StringUtil;
import com.cspm.ahjy.bc.office.util.UnitConvertUtil;
import com.cspm.ahjy.bc.office.word.domain.MSAction;
import com.cspm.ahjy.bc.office.word.domain.MSActionType;
import com.cspm.ahjy.bc.office.word.domain.MSBody;
import com.cspm.ahjy.bc.office.word.domain.MSFont;
import com.cspm.ahjy.bc.office.word.domain.MSPicture;

/**
 * 图片操作
 * 
 * @author ServerZhang
 * @date 2017年9月28日
 */
public class PictureUtil {
	
	private static final DecimalFormat df = new DecimalFormat("######0.00");

	/**
	 * 添加图片
	 * 
	 * @param font2
	 * @return
	 * @author ServerZhang
	 * @date 2017年9月28日
	 */
	public static List<MSAction> addPicture(MSPicture picture,
			Integer paragraphNo) {

		return getPictureStyle(picture, paragraphNo);

	}

	/**
	 * 段落中的图片比较
	 * 
	 * @param picture1
	 * @param picture2
	 * @return
	 * @author ServerZhang
	 * @date 2017年9月29日
	 */
	public static List<MSAction> comparePicture(MSPicture picture1,
			MSPicture picture2, Integer paragraphNo) {
		List<MSAction> actions = new ArrayList<MSAction>();

		Integer[] paragraphNos = new Integer[1];
		if (paragraphNo != null) {
			paragraphNos[0] = paragraphNo;
		}

		String title1 = picture1.getTitle();
		String title2 = picture2.getTitle();

		String msoPosition1 = picture1.getMsoPosition();
		String msoPosition2 = picture2.getMsoPosition();

		String encircle1 = picture1.getEncircle();
		String encircle2 = picture2.getEncircle();

		Double width1 = picture1.getWidth();
		Double width2 = picture2.getWidth();

		Double height1 = picture1.getHeight();
		Double height2 = picture2.getHeight();

		String strokeStyle1 = picture1.getStrokeStyle();
		String strokeStyle2 = picture2.getStrokeStyle();

		String strokeColor1 = picture1.getStrokeColor();
		String strokeColor2 = picture2.getStrokeColor();

		Integer strokeWeight1 = picture1.getStrokeWeight();
		Integer strokeWeight2 = picture2.getStrokeWeight();
		
		Double zoomWidth1 = picture1.getZoomWidth();
		Double zoomWidth2 = picture2.getZoomWidth();

		if (!StringUtils.isEmpty(msoPosition2)
				&& !msoPosition2.equals(msoPosition1)) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_msoPosition");
			action.setText("/picture/");
			actionType.setTypeValue(msoPosition2);
			action.setParagraphNos(paragraphNos);
			
			String content = "水平对齐方式为“";
			AlignEnum byValue = AlignEnum.getByValue(msoPosition2);
			if (byValue != null) {
				content += byValue.getText();
			}else {
				content += msoPosition2;
			}
			content += "”";
			
			actionType.setTypeContent(content);
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (!StringUtils.isEmpty(encircle2) && !encircle2.equals(encircle1)) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_encircle");
			action.setText("/picture/");
			actionType.setTypeValue(encircle2);
			action.setParagraphNos(paragraphNos);
			actionType.setTypeContent("环绕方式为 " + encircle2);
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (!StringUtils.isEmpty(strokeStyle2)
				&& !strokeStyle2.equals(strokeStyle1)) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_strokeStyle");
			action.setText("/picture/");
			actionType.setTypeValue(strokeStyle2);
			action.setParagraphNos(paragraphNos);
			actionType.setTypeContent("线条样式为 " + strokeStyle2);
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (!StringUtils.isEmpty(strokeColor2)
				&& !strokeColor2.equals(strokeColor1)) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_strokeColor");
			action.setText("/picture/");
			actionType.setTypeValue(strokeColor2);
			action.setParagraphNos(paragraphNos);
			
			String content = "线条颜色为“";
			ColorEnum byValue = ColorEnum.getByValue(strokeColor2);
			if (byValue != null) {
				content += byValue.getName();
			}else {
				content += strokeColor2;
			}
			content += "”";
			
			actionType.setTypeContent(content);
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (!StringUtils.isEmpty(strokeWeight2)
				&& !strokeWeight2.equals(strokeWeight1)) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_strokeWeight");
			action.setText("/picture/");
			actionType.setTypeValue(strokeWeight2);
			action.setParagraphNos(paragraphNos);
			actionType.setTypeContent("线条粗细为 "
					+ UnitConvertUtil.standar2PT(strokeWeight2));
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (zoomWidth2 != null && !zoomWidth2.equals(zoomWidth1)) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_zoomWidth");
			action.setText("/picture/");
			actionType.setTypeValue(zoomWidth2);
			action.setParagraphNos(paragraphNos);
			actionType.setTypeContent("缩放比例为“"+(zoomWidth2*100)+"%”");
			action.setMsActionType(actionType);
			actions.add(action);
		}

		return actions;
	}

	/**
	 * 
	 * @param answer
	 *            标准答案文档
	 * @param task
	 *            学生提交文档
	 * @param paragraphNums
	 *            匹配的段落
	 * @param text
	 *            匹配的文字
	 * @param settings
	 *            对应的文字操作
	 * @return
	 * @author ServerZhang
	 * @date 2017年9月22日
	 */
	public static Map<String, Boolean> mark(MSBody answer, MSBody work,
			List<Integer> paragraphNums, String text,
			Map<String, Object> settings) {
		Map<String, Boolean> map = new HashMap<String, Boolean>();

		if (null == paragraphNums || paragraphNums.size() <= 0
				|| null == settings || settings.size() <= 0) {
			return map;
		}

		List<MSFont> fonts1 = BodyUtil.getFonts(answer, paragraphNums, text);
		List<MSFont> fonts2 = BodyUtil.getFonts(work, paragraphNums, text);

		if (fonts2.size() <= 0) {
			return map;
		}

		Set<String> keySet = settings.keySet();
		for (String key : keySet) {
			Object object = settings.get(key);
			if (null == object) {
				continue;
			}
			String objStr = object.toString();
			map.put(key, true);// 默认此项操作正确
			if (key.equals("font")) {
				Iterator<MSFont> iterator = fonts2.iterator();
				while (iterator.hasNext()) {
					MSFont next = iterator.next();
					if (!objStr.equals(next.getFontName())) {// 只要有一处不匹配视为此项操作不正确
						map.put(key, false);
						System.out.println("未将指定文字“" + text + "”设置字体为："
								+ objStr);
						break;
					}
				}
			} else if (key.equals("size")) {
				Iterator<MSFont> iterator = fonts2.iterator();
				while (iterator.hasNext()) {
					MSFont next = iterator.next();
					Integer parseInt = Integer.parseInt(objStr);
					if (!parseInt.equals(next.getFontSize())) {// 只要有一处不匹配视为此项操作不正确
						map.put(key, false);
						System.out.println("未将指定文字“" + text + "”设置大小为："
								+ objStr);
						break;
					}
				}
			} else if (key.equals("color")) {
				Iterator<MSFont> iterator = fonts2.iterator();
				while (iterator.hasNext()) {
					MSFont next = iterator.next();
					if (!objStr.equals(next.getColor())) {// 只要有一处不匹配视为此项操作不正确
						map.put(key, false);
						System.out.println("未将指定文字“" + text + "”设置颜色为："
								+ objStr);
						break;
					}
				}
			} else if (key.equals("bold")) {
				Iterator<MSFont> iterator = fonts2.iterator();
				while (iterator.hasNext()) {
					MSFont next = iterator.next();
					Boolean parseBoolean = Boolean.parseBoolean(objStr);
					if (!parseBoolean.equals(next.getBold())) {// 只要有一处不匹配视为此项操作不正确
						map.put(key, false);
						if (parseBoolean) {
							System.out.println("未将指定文字“" + text + "”加粗");
						} else {
							System.out.println("未将指定文字“" + text + "”取消加粗");
						}
						break;
					}
				}
			} else if (key.equals("italic")) {
				Iterator<MSFont> iterator = fonts2.iterator();
				while (iterator.hasNext()) {
					MSFont next = iterator.next();
					Boolean parseBoolean = Boolean.parseBoolean(objStr);
					if (!parseBoolean.equals(next.getItalic())) {// 只要有一处不匹配视为此项操作不正确
						map.put(key, false);
						if (parseBoolean) {
							System.out.println("未将指定文字“" + text + "”设置为斜体");
						} else {
							System.out.println("未将指定文字“" + text + "”取消斜体");
						}
						break;
					}
				}
			} else if (key.equals("underline")) {
				Iterator<MSFont> iterator = fonts2.iterator();
				while (iterator.hasNext()) {
					MSFont next = iterator.next();
					if (!objStr.equals(next.getUnderline())) {// 只要有一处不匹配视为此项操作不正确
						map.put(key, false);
						System.out.println("未将指定文字“" + text + "”按要求设置下划线样式");
						break;
					}
				}
			} else if (key.equals("underlineColor")) {
				Iterator<MSFont> iterator = fonts2.iterator();
				while (iterator.hasNext()) {
					MSFont next = iterator.next();
					if (!objStr.equals(next.getUnderlineColor())) {// 只要有一处不匹配视为此项操作不正确
						map.put(key, false);
						System.out.println("未将指定文字“" + text + "”按要求设置下划线颜色");
						break;
					}
				}
			}
		}

		return map;

	}

	/**
	 * 从<v:pict>标签下获取图片
	 * @param pictElement
	 * @param path
	 * @return
	 * @author ServerZhang
	 * @date 2017年10月18日
	 */
	public static MSPicture getPicture4Pict(Element pictElement, String path) {
		MSPicture picture = new MSPicture();

		Double newWidth = null;//图片宽（厘米）
		Double oldWidth = null;//图片原宽（厘米）
		Double newHeight = null;//图片高（厘米）
		Double oldHeight = null;//图片原宽（厘米）
		
		Element shapeElement = pictElement.element("shape");//
		if (null == shapeElement) {
			return picture;
		}
		
		Attribute style = shapeElement.attribute("style");
		if (style != null) {
			String text = style.getText();
			Map<String, String> map = StringUtil.toMap(text);
			String msoPosition = map.get("mso-position-horizontal");
			if (!StringUtils.isEmpty(msoPosition)) {
				picture.setMsoPosition(msoPosition);
			}
			String width = map.get("width");
			if (!StringUtils.isEmpty(width)) {
				Integer standard = UnitConvertUtil.convert2Standard(width);
				String standar2cm = UnitConvertUtil.standar2CM(standard);
				if (!StringUtils.isEmpty(standar2cm)) {
					Double parseDouble = Double.parseDouble(standar2cm.replaceAll("厘米", ""));
					newWidth = Double.parseDouble(df.format(parseDouble));
				}
				
				picture.setWidth(newWidth);
			}
			String height = map.get("height");
			if (!StringUtils.isEmpty(height)) {
				Integer standard = UnitConvertUtil.convert2Standard(height);
				String standar2cm = UnitConvertUtil.standar2CM(standard);
				if (!StringUtils.isEmpty(standar2cm)) {
					Double parseDouble = Double.parseDouble(standar2cm.replaceAll("厘米", ""));
					newHeight = Double.parseDouble(df.format(parseDouble));
				}
				
				picture.setHeight(newHeight);
			}
			
			//环绕方式：
			Element wrapElement = shapeElement.element("wrap");
			if (wrapElement != null) {
				Attribute type = wrapElement.attribute("type");
				if (type != null) {
					switch (type.getText()) {
					case "square":
						picture.setEncircle("四周型");
						break;
					case "tight":
						picture.setEncircle("紧密型");
						break;

					default:
						break;
					}
				}
			} else {
				String position = map.get("position");
				String zIndex = map.get("z-index");
				if (StringUtils.isEmpty(position)) {
					picture.setEncircle("嵌入型");
				}else {
					if ("1".equals(zIndex)) {
						picture.setEncircle("浮于文字上方");
					}else if ("-1".equals(zIndex)) {
						picture.setEncircle("衬于文字下方");
					}
				}
			}
		}
		Attribute strokecolor = shapeElement.attribute("strokecolor");
		if (strokecolor != null) {
			picture.setStrokeColor(strokecolor.getText());
		}
		Attribute strokeweight = shapeElement.attribute("strokeweight");
		if (strokeweight != null) {
			Integer standard = UnitConvertUtil
					.convert2Standard(strokeweight.getText());
			picture.setStrokeWeight(standard);
		}

		String picTitle = null;
		Element imgElement = shapeElement.element("imagedata");
		if (imgElement != null) {
			Attribute title = imgElement.attribute("title");
			if (title != null) {
				picTitle = title.getText();
				picture.setTitle(picTitle);
			}
			// 有些属性即可判断有冲蚀效果，至于具体值不需要关心
			Attribute gain = imgElement.attribute("gain");
			if (gain != null) {
				picture.setAblation(Boolean.TRUE);
			}
		}

		Element strokeElement = shapeElement.element("stroke");
		if (strokeElement != null) {
			Attribute dashstyle = strokeElement.attribute("dashstyle");
			if (dashstyle != null) {
				picture.setStrokeStyle(dashstyle.getText());
			}
		}
		//获取原图宽高
		Element binData = pictElement.element("binData");
		if (binData != null) {
			String data = (String)binData.getData();
			
			if (!StringUtils.isEmpty(data) && picTitle != null) {
				//TODO 判断是否是jpg图片
				Boolean isJpg = ImageFileUtil.isJPG4BinData(data);
				if (isJpg) {
					String picPath = path+picTitle+".jpg";
					File file = new File(picPath);
					if (!file.exists()) {//不存在，则读取图片数据到文件
						FileOutputStream outStream = null;
						BASE64Decoder decoder = new BASE64Decoder();
						try {
							outStream = new FileOutputStream(picPath);
							
							byte[] decodeBuffer = decoder.decodeBuffer(data);  
							outStream.write(decodeBuffer);
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					//读取图片原始高宽
					Map<String, Double> jpgWH = ImageFileUtil.getJpgWH(file);
					oldWidth = jpgWH.get("width");
					oldHeight = jpgWH.get("height");
					
					picture.setOriginalWidth(oldHeight);
					picture.setOriginalHeight(oldHeight);
					
					if (oldWidth != null && newWidth != null
							&& !oldWidth.equals(0.0) && !newWidth.equals(0.0)) {
						Double zoomWidth = newWidth / oldWidth;
						zoomWidth = Double.parseDouble(df.format(zoomWidth));
						
						if (!zoomWidth.equals(1.0)) {						
							picture.setZoomWidth(zoomWidth);
						}
					}
					if (oldHeight != null && newHeight != null
							&& !oldHeight.equals(0.0) && !newHeight.equals(0.0)) {
						Double zoomHeight = newHeight / oldHeight;
						zoomHeight = Double.parseDouble(df.format(zoomHeight));
						
						if (!zoomHeight.equals(1.0)) {						
							picture.setZoomHeight(zoomHeight);
						}
					}
					
					
				}else {
					//TODO 非jpg图片处理
System.out.println("非jpg图片无法处理！！！");
				}
			}
		}

		return picture;
	}

	/**
	 * 获取图片样式
	 * 
	 * @param picture
	 * @param paragraphNo
	 * @return
	 * @author ServerZhang
	 * @date 2017年10月11日
	 */
	private static List<MSAction> getPictureStyle(MSPicture picture,
			Integer paragraphNo) {
		List<MSAction> actions = new ArrayList<MSAction>();
		
		if (picture == null) {
			return actions;
		}

		Integer[] paragraphNos = new Integer[1];
		if (paragraphNo != null) {
			paragraphNos[0] = paragraphNo;
		}

		String title = picture.getTitle();
		String msoPosition = picture.getMsoPosition();
		String encircle = picture.getEncircle();
		Double width = picture.getWidth();
		Double height = picture.getHeight();
		String strokeStyle = picture.getStrokeStyle();
		String strokeColor = picture.getStrokeColor();
		Integer strokeWeight = picture.getStrokeWeight();
		Double zoomWidth = picture.getZoomWidth();

		if (msoPosition != null) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_msoPosition");
			action.setText("/picture/");
			actionType.setTypeValue(msoPosition);
			action.setInsert(Boolean.TRUE);
			action.setParagraphNos(paragraphNos);
			
			String content = "水平对齐方式为“";
			AlignEnum byValue = AlignEnum.getByValue(msoPosition);
			if (byValue != null) {
				content += byValue.getText();
			}else {
				content += msoPosition;
			}
			content += "”";
			
			actionType.setTypeContent(content);
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (encircle != null) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_encircle");
			action.setText("/picture/");
			actionType.setTypeValue(encircle);
			action.setInsert(Boolean.TRUE);
			action.setParagraphNos(paragraphNos);
			actionType.setTypeContent("环绕方式为 " + encircle);
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (strokeStyle != null) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_strokeStyle");
			action.setText("/picture/");
			actionType.setTypeValue(strokeStyle);
			action.setInsert(Boolean.TRUE);
			action.setParagraphNos(paragraphNos);
			actionType.setTypeContent("线条样式为 " + strokeStyle);
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (strokeColor != null) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_strokeColor");
			action.setText("/picture/");
			actionType.setTypeValue(strokeColor);
			action.setInsert(Boolean.TRUE);
			action.setParagraphNos(paragraphNos);
			
			String content = "线条颜色为“";
			ColorEnum byValue = ColorEnum.getByValue(strokeColor);
			if (byValue != null) {
				content += byValue.getName();
			}else {
				content += strokeColor;
			}
			content += "”";
			
			actionType.setTypeContent(content);
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (strokeWeight != null) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_strokeWeight");
			action.setText("/picture/");
			actionType.setTypeValue(strokeWeight);
			action.setInsert(Boolean.TRUE);
			action.setParagraphNos(paragraphNos);
			actionType.setTypeContent("线条粗细为 " + strokeWeight);
			action.setMsActionType(actionType);
			actions.add(action);
		}
		if (zoomWidth != null && !zoomWidth.equals(1.0)) {
			MSAction action = new MSAction();
			MSActionType actionType = new MSActionType();
			actionType.setType("font_picture_zoomWidth");
			action.setText("/picture/");
			actionType.setTypeValue(zoomWidth);
			action.setInsert(Boolean.TRUE);
			action.setParagraphNos(paragraphNos);
			actionType.setTypeContent("缩放比例为“"+(zoomWidth*100)+"%”");
			action.setMsActionType(actionType);
			actions.add(action);
		}

		return actions;
	}
	
	
}
